const OSS = require('ali-oss')
const path = require("path")
const fs = require('fs')

// 从环境变量中获取配置，支持 Gitee Go 流水线变量
const config = {
  region: process.env.OSS_REGION || 'oss-cn-shanghai',
  accessKeyId: process.env.OSS_ACCESS_KEY_ID || '',
  accessKeySecret: process.env.OSS_ACCESS_KEY_SECRET || '',
  bucket: process.env.OSS_BUCKET || 'zhixiaocloud',
  authorizationV4: true
};

// 验证必要的配置是否存在
function validateConfig() {
  console.log('=== 环境变量检查 ===');
  console.log('OSS_REGION:', config.region);
  console.log('OSS_BUCKET:', config.bucket);
  console.log('OSS_ACCESS_KEY_ID:', config.accessKeyId ? `${config.accessKeyId.substring(0, 8)}...` : '未设置');
  console.log('OSS_ACCESS_KEY_SECRET:', config.accessKeySecret ? '已设置' : '未设置');
  
  const requiredVars = ['OSS_ACCESS_KEY_ID', 'OSS_ACCESS_KEY_SECRET'];
  const missingVars = requiredVars.filter(varName => !process.env[varName]);
  
  if (missingVars.length > 0) {
    console.error('❌ 缺少必要的环境变量:', missingVars.join(', '));
    console.error('请在 Gitee Go 项目设置中配置这些变量');
    process.exit(1);
  }
  
  console.log('✅ 环境变量验证通过');
}

// 验证配置
validateConfig();

const client = new OSS(config);

// 自定义请求头
const headers = {
  // 指定Object的存储类型。
  'x-oss-storage-class': 'Standard',
  // 指定Object的访问权限为公共读，允许通过域名直接访问。
  'x-oss-object-acl': 'public-read',
  // 指定PutObject操作时是否覆盖同名目标Object。此处设置为false，表示允许覆盖同名Object。
  'x-oss-forbid-overwrite': 'false',
};

// 根据文件扩展名获取正确的 Content-Type
function getContentType(filePath) {
  const ext = path.extname(filePath).toLowerCase();
  const contentTypes = {
    '.html': 'text/html; charset=utf-8',
    '.htm': 'text/html; charset=utf-8',
    '.css': 'text/css; charset=utf-8',
    '.js': 'application/javascript; charset=utf-8',
    '.json': 'application/json; charset=utf-8',
    '.png': 'image/png',
    '.jpg': 'image/jpeg',
    '.jpeg': 'image/jpeg',
    '.gif': 'image/gif',
    '.svg': 'image/svg+xml',
    '.ico': 'image/x-icon',
    '.txt': 'text/plain; charset=utf-8',
    '.xml': 'application/xml; charset=utf-8',
    '.pdf': 'application/pdf',
    '.zip': 'application/zip',
    '.woff': 'font/woff',
    '.woff2': 'font/woff2',
    '.ttf': 'font/ttf',
    '.eot': 'application/vnd.ms-fontobject'
  };
  return contentTypes[ext] || 'application/octet-stream';
}

// 递归上传目录中的所有文件
async function uploadDirectory(localDir, ossPrefix = '') {
  const files = fs.readdirSync(localDir);
  
  for (const file of files) {
    const localPath = path.join(localDir, file);
    const ossPath = ossPrefix ? `${ossPrefix}/${file}` : file;
    
    if (fs.statSync(localPath).isDirectory()) {
      // 如果是目录，递归上传
      await uploadDirectory(localPath, ossPath);
    } else {
      // 如果是文件，上传到OSS
      try {
        console.log(`正在上传: ${localPath} -> ${ossPath}`);
        
        // 为每个文件设置正确的 Content-Type
        const fileHeaders = {
          ...headers,
          'Content-Type': getContentType(localPath)
        };
        
        const result = await client.put(ossPath, localPath, { headers: fileHeaders });
        console.log(`✓ 上传成功: ${ossPath} (${getContentType(localPath)})`);
      } catch (error) {
        console.error(`✗ 上传失败: ${ossPath}`, error.message);
      }
    }
  }
}

async function deploy() {
  try {
    const distPath = path.normalize('.vitepress/dist');
    
    // 检查目录是否存在
    if (!fs.existsSync(distPath)) {
      throw new Error(`构建目录不存在: ${distPath}，请先运行 npm run docs:build`);
    }
    
    console.log('开始上传文件到阿里云OSS...');
    await uploadDirectory(distPath);
    console.log('所有文件上传完成！');
  } catch (e) {
    console.error('部署失败:', e.message);
  }
}

deploy();